<template>
  <div class="page-container">
    <div class="page-header">
      <div class="page-header-actions">
        <el-breadcrumb separator="/">
          <el-breadcrumb-item :to="{ path: '/workflow-templates' }">工作流模板管理</el-breadcrumb-item>
          <el-breadcrumb-item>版本历史</el-breadcrumb-item>
        </el-breadcrumb>
        <div class="action-buttons">
          <el-button @click="handleBack">
            <el-icon><Back /></el-icon>
            返回
          </el-button>
        </div>
      </div>
    </div>

    <el-card>
      <template #header>
        <div class="card-header">
          <span class="card-title">{{ templateName }} - 版本历史</span>
        </div>
      </template>

      <el-table
        :data="templateStore.versionHistory"
        v-loading="templateStore.loading"
        stripe
      >
        <el-table-column prop="version" label="版本号" width="100">
          <template #default="{ row }">
            <el-tag :type="row.version === latestVersion ? 'success' : 'info'">
              v{{ row.version }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="change_log" label="变更说明" min-width="250" show-overflow-tooltip />
        <el-table-column prop="parent_version_id" label="父版本" width="120">
          <template #default="{ row }">
            {{ row.parent_version_id ? `v${getParentVersion(row.parent_version_id)}` : '无（初始版本）' }}
          </template>
        </el-table-column>
        <el-table-column prop="created_by" label="创建人" width="120">
          <template #default="{ row }">
            {{ row.created_by || '系统' }}
          </template>
        </el-table-column>
        <el-table-column prop="created_at" label="创建时间" width="180">
          <template #default="{ row }">
            {{ formatDate(row.created_at) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="350" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="handleViewVersion(row)">查看详情</el-button>
            <el-button
              size="small"
              type="warning"
              @click="handleCompare(row)"
              :disabled="row.parent_version_id === null"
            >
              对比父版本
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleRollback(row)"
              :disabled="row.version === latestVersion"
            >
              回滚
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useWorkflowTemplateStore } from '@/stores/workflowTemplate'
import dayjs from 'dayjs'

const router = useRouter()
const route = useRoute()
const templateStore = useWorkflowTemplateStore()

const templateId = ref(parseInt(route.params.id))
const templateName = ref('')

const latestVersion = computed(() => {
  if (templateStore.versionHistory.length === 0) return 0
  return Math.max(...templateStore.versionHistory.map(v => v.version))
})

const formatDate = (date) => {
  return date ? dayjs(date).format('YYYY-MM-DD HH:mm:ss') : ''
}

const getParentVersion = (parentVersionId) => {
  const parent = templateStore.versionHistory.find(v => v.id === parentVersionId)
  return parent ? parent.version : '未知'
}

const fetchVersionHistory = async () => {
  try {
    await templateStore.fetchVersionHistory(templateId.value)
    // 获取模板名称
    if (templateStore.versionHistory.length > 0) {
      templateName.value = templateStore.versionHistory[0].name
    }
  } catch (error) {
    console.error('获取版本历史失败:', error)
    ElMessage.error('获取版本历史失败')
  }
}

const handleBack = () => {
  router.push('/workflow-templates')
}

const handleViewVersion = (row) => {
  router.push(`/workflow-templates/${templateId.value}/versions/${row.version}`)
}

const handleCompare = (row) => {
  if (!row.parent_version_id) {
    ElMessage.warning('初始版本无父版本可对比')
    return
  }
  const parentVersion = getParentVersion(row.parent_version_id)
  router.push({
    path: `/workflow-templates/${templateId.value}/diff`,
    query: {
      version1: parentVersion,
      version2: row.version
    }
  })
}

const handleRollback = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要回滚到版本 v${row.version} 吗？这将创建一个新版本。`,
      '确认回滚',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await templateStore.rollbackToVersion(templateId.value, row.version)
    ElMessage.success('回滚成功，已创建新版本')
    fetchVersionHistory()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('回滚失败:', error)
      ElMessage.error(error.response?.data?.detail || '回滚失败')
    }
  }
}

onMounted(() => {
  fetchVersionHistory()
})
</script>

<style lang="scss" scoped>
.page-header-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.card-title {
  font-size: 16px;
  font-weight: 600;
}

.action-buttons {
  display: flex;
  gap: 10px;
}
</style>
